package com.qf.springbootproject.aspect;

import com.qf.springbootproject.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class LogAspectHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 定义一个切面，拦截com.glls.controller包和子包下的所有方法
     */
    @Pointcut("execution(* com.qf.springbootproject.service..*.*(..))")
    public void pointCut() {}

    @Pointcut("execution(* com.qf.springbootproject.controller..*.*(..))")
    public void pointCut1() {}

    @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping)")
    public void annotationCut() {}

    /**
     * 在上面定义的切面方法之前执行该方法
     * @param joinPoint jointPoint
     *
     * JointPoint 对象很有用，可以用它来获取一个签名，然后利用签名可以获取请求的包名、方法名，
     * 包括参数（通过 `joinPoint.getArgs()` 获取）等等。
     */

    @Before("pointCut()")
    public void doBefore(JoinPoint joinPoint) {
        logger.info("====doBefore方法进入了====");

        // 获取签名
        Signature signature = joinPoint.getSignature();
        // 获取切入的包名
        String declaringTypeName = signature.getDeclaringTypeName();
        // 获取即将执行的方法名
        String funcName = signature.getName();
        logger.info("即将执行方法为: {}，属于{}包", funcName, declaringTypeName);

        // 也可以用来记录一些信息，比如获取请求的url和ip
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 获取请求url
        String url = request.getRequestURL().toString();
        // 获取请求ip
        String ip = request.getRemoteAddr();
        logger.info("用户请求的url为：{}，ip地址为：{}", url, ip);
    }

    /**
     * 在上面定义的切面方法之后执行该方法
     * @param joinPoint jointPoint
     */
    @After("pointCut()")
    public void doAfter(JoinPoint joinPoint) {

        logger.info("====doAfter方法进入了====");
        Signature signature = joinPoint.getSignature();
        String method = signature.getName();
        logger.info("方法{}已经执行完", method);
    }

    /**
     * 在上面定义的切面方法返回后执行该方法，可以捕获返回对象或者对返回对象进行增强
     * @param joinPoint joinPoint
     * @param result result
     */

    @AfterReturning(pointcut = "pointCut()", returning = "result")
    public void doAfterReturning(JoinPoint joinPoint, Object result) {

        Signature signature = joinPoint.getSignature();
        String classMethod = signature.getName();

        logger.info("方法{}执行完毕，返回参数为：{}", classMethod, result);
        // 实际项目中可以根据业务做具体的返回值增强
        logger.info("对返回参数进行业务上的增强：{}", result + "增强版");
    }


    /**
     * 在上面定义的切面方法执行抛异常时，执行该方法
     * @param joinPoint jointPoint
     * @param ex ex
     */
    @AfterThrowing(pointcut = "pointCut()", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, Throwable ex) {
        Signature signature = joinPoint.getSignature();
        String method = signature.getName();
        // 处理异常的逻辑
        logger.info("执行方法{}出错，异常为：{}", method, ex);
    }

//    @Around(value = "pointCut1()")
    public Object  around(ProceedingJoinPoint joinPoint){
        //获取方法的参数值数组
        Object[] args = joinPoint.getArgs();
        log.info("修改之前的请求参数为{}",args);

        // 得到其方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        //获取方法的参数类型数组
        Class[] parameterTypes = signature.getParameterTypes();

        if(User.class.isAssignableFrom(parameterTypes[parameterTypes.length-1])){
            User user = new User("8","xxx","xxx");

            args[args.length-1] = user;
        }

        log.info("修改之后的请求参数{}",args);

        System.out.println("环绕前置通知");


        Object result = null;

        //目标方法执行
        try {
            result = joinPoint.proceed(args);


            log.info("相应结果是{}",result);

            log.info("环绕返回通知");
        } catch (Throwable throwable) {
            log.info("环绕异常通知");
            throwable.printStackTrace();
        }finally {
            log.info("环绕最终通知");
        }

        result = new User("9","幕后黑手","8888");
        //如果这里返回null   则目标对象实际返回值也会被置为null
        return result;
    }

}
